package gb.struct;

import java.util.*;

public class Monomial implements Cloneable{
    private ArrayList<Integer> powers;
    private double coefficient;
    public static int SIZE = 1;
    
    public Monomial(double coef) {
        powers = new ArrayList<Integer>(SIZE);
        coefficient = coef;
    }
    
    public void addPower(Integer power) {
        powers.add(power);
    }
    
    public void setPower(Integer power, int pos) {
        powers.set(pos, power);
    }
 
    public Integer getPower(int pos) {
        return powers.get(pos);
    }
    
    public double getCoefficient() {
        return coefficient;
    }

    public void setCoefficient(double coefficient) {
        this.coefficient = coefficient;
    }
    
    public String toString() {
        StringBuffer buf = new StringBuffer("" + coefficient);
        for (int i = 0; i < powers.size(); i++) {
        	if(powers.get(i) != 0) {
        		buf.append("x").append(i+1).append("^").append(powers.get(i));
        	}
        }
        return buf.toString();
    }
    
    public int sumOfPowers() {
        int sum = 0;
        for (int i = 0; i< powers.size(); i++) {
            sum += powers.get(i);
        }
        return sum;
    }
    
    public boolean equals(Object ob) {
        
        if (ob instanceof Monomial && // we equal on monomial alone 
                match((Monomial) ob) &&  // equals is a stronger relation than matching
                ((Monomial) ob).getCoefficient() == coefficient) { // same coefficient is the last condition
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * match appropriate for addition. might be modified ...
     * @param m a monomial to match to
     * @return true if contains same powers, false otherwise
     */
    public boolean match(Monomial m) {
        boolean result = true; //assume m is a matching monomial
        
        if (powers.size() == m.getSize()) {
            for (int i = 0; i < powers.size() && result; i++) {
                if (m.getPower(i) != powers.get(i)) {
                    result = false;
                }
            }
        }
        
        return result;
    }
    
    public int getSize() {
        return powers.size();
    }
    
    public Object clone() {
        Monomial mc = new Monomial(coefficient);
        for (int i = 0; i < powers.size(); i++) {
            mc.addPower(powers.get(i));
        }
        return mc;
    }
    
}
